package com.goldsprite.projecttemplategenerator.test;

import java.io.*;
import java.util.*;

public class PackageNameReplacer {
	public static void replacePackageNames(File directory, String oldPackageName, String newPackageName) throws IOException {
		Queue<File> filesQueue = new LinkedList<>();
		filesQueue.add(directory);

		while (!filesQueue.isEmpty()) {
			File currentFile = filesQueue.poll();

			if (currentFile.isDirectory()) {
				File[] children = currentFile.listFiles();
				if (children != null) {
					filesQueue.addAll(Arrays.asList(children));
				}
			} else if (currentFile.isFile()) {
				replaceInFile(currentFile, oldPackageName, newPackageName);
			}
		}
	}

	private static void replaceInFile(File file, String oldText, String newText) throws IOException {
		String content;
		try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
			StringBuilder builder = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null) {
				builder.append(line).append("\n");
			}
			content = builder.toString();
		}

		if (content.contains(oldText)) {
			content = content.replace(oldText, newText);
			try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
				writer.write(content);
			}
		}
	}
}
